import 'dart:convert';
import 'dart:math';
import 'package:app/api/api.dart';
import 'package:app/extensions/string_extensions.dart';
import 'package:app/responsive.dart';
import 'package:app/utils/aes_utils.dart';
import 'package:app/utils/http_util.dart';
import 'package:flutter/material.dart';
import 'package:flutter_swiper_null_safety/flutter_swiper_null_safety.dart';

class DesktopIndexMainViewModel extends StatefulWidget {
  const DesktopIndexMainViewModel({super.key});
  @override
  State<StatefulWidget> createState() {
    return DesktopIndexMainView();
  }
}

/* 

,
 */
class DesktopIndexMainView extends State<DesktopIndexMainViewModel> {
  int headerCount = 1;
  int footerCount = 1;
  final HttpUtil _httpUtil = HttpUtil();
  List<dynamic> banners = [];
  List<dynamic> articles = [];
  bool hasMore = true;
  bool backTopShow = false;
  final ScrollController _scrollController = ScrollController();
  double articleListWidth = 625;
  double infomationListWidth = 280;
  double middleScale = 1;
  @override
  void initState() {
    super.initState();
    _scrollController.addListener(() {
      bool currentShow = backTopShow;
      backTopShow = _scrollController.position.pixels > 400;
      if (backTopShow != currentShow) {
        setState(() {});
      }
    });
    Future<String?> result = _httpUtil.get(Apis.getBanner);
    result
        .then(
          (value) {
            setState(() {
              Map<String, dynamic> map = jsonDecode(value!);
              var data = jsonDecode(aesDecrypted(map["data"]));
              banners.clear();
              for (Map<String, dynamic> element in data) {
                banners.add(element);
              }
            });
          },
        )
        .onError((error, stackTrace) {})
        .catchError((err) {});
    Future<GResponse> postList = _httpUtil.post(Apis.blog, params: {
      "page": 1,
    });
    postList.then((value) {
      if (value.success) {
        setState(() {
          articles.clear();
          for (Map<String, dynamic> element in value.data["data"]) {
            articles.add(element);
          }
        });
      }
    }).catchError((err) {});
  }

  @override
  Widget build(BuildContext context) {
    middleScale = _Style.getMiddleScale(context);
    articleListWidth = 625 * middleScale;
    infomationListWidth = 280 * middleScale;
    return Stack(
      children: [
        SingleChildScrollView(
          controller: _scrollController,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              //不给宽度会报 Vertical viewport was given unbounded width.
              SizedBox(
                width: articleListWidth,
                child: ListView.separated(
                  scrollDirection: Axis.vertical,
                  shrinkWrap: true,
                  physics: const NeverScrollableScrollPhysics(),
                  itemCount: headerCount + articles.length + footerCount,
                  itemBuilder: (context, index) {
                    return getView(context, index);
                  },
                  separatorBuilder: (BuildContext context, int index) {
                    return Divider(
                        height: 1,
                        color: index >= 1
                            ? const Color(0xfff0f0f0)
                            : Colors.white);
                  },
                ),
              ),
              Container(
                  width: infomationListWidth,
                  alignment: Alignment.topCenter,
                  margin: const EdgeInsets.fromLTRB(24, 26, 0, 0),
                  child: Column(
                    children: [
                      getRigthItem(
                          "http://qiniuyun.xiaotuzhi.top/banner-s-daily-e6f6601abc495573ad37f2532468186f.png"),
                      getRigthItem(
                          "http://qiniuyun.xiaotuzhi.top/banner-s-club-aa8bdf19f8cf729a759da42e4a96f366.png"),
                      getRigthItem(
                          "http://qiniuyun.xiaotuzhi.top/banner-s-7-1a0222c91694a1f38e610be4bf9669be.png"),
                      getRigthItem(
                          "http://qiniuyun.xiaotuzhi.top/banner-s-5-4ba25cf5041931a0ed2062828b4064cb.png"),
                      getDownLoadAppView(),
                      getRecomendUserView()
                    ],
                  ))
            ],
          ),
        ),
        backTopShow
            ? Positioned(
                right: 50,
                bottom: 50,
                child: Container(
                  width: 52,
                  height: 52,
                  decoration: const BoxDecoration(
                      color: Colors.white,
                      border: Border.symmetric(
                          vertical:
                              BorderSide(color: Color(0xffdcdcdc), width: 1),
                          horizontal:
                              BorderSide(color: Color(0xffdcdcdc), width: 1))),
                  child: const Icon(Icons.expand_less),
                ))
            : const SizedBox.shrink()
      ],
    );
  }

  Widget getView(BuildContext context, int index) {
    if (index <= headerCount - 1) {
      return getHeaderView(context, index);
    } else if (index >= headerCount + articles.length) {
      return getFooterView(context, index - headerCount - articles.length);
    } else {
      return getArticleItemView(context, index - headerCount);
    }
  }

  Widget getFooterView(BuildContext context, int index) {
    return Column(
      children: [
        hasMore
            ? Container(
                alignment: Alignment.center,
                margin: const EdgeInsets.symmetric(vertical: 24, horizontal: 0),
                width: double.infinity,
                height: 40,
                decoration: const BoxDecoration(
                    color: Color(0xffa5a5a5),
                    borderRadius: BorderRadius.all(Radius.elliptical(20, 20))),
                child: const Text(
                  "阅读更多",
                  style: TextStyle(color: Colors.white, fontSize: 15),
                ),
              )
            : const Text("没有更多内容了"),
        SizedBox.fromSize(
          size: const Size(double.infinity, 48),
        ),
        Flex(
          direction: Axis.horizontal,
          children: const [
            Text(
              "关于我们",
              style: _Style.linkStyle,
            ),
            Text(
              " · ",
              style: _Style.linkStyle,
            ),
            Text(
              "联系我们",
              style: _Style.linkStyle,
            ),
            Text(
              " · ",
              style: _Style.linkStyle,
            ),
            Text(
              "加入我们",
              style: _Style.linkStyle,
            ),
            Text(
              " · ",
              style: _Style.linkStyle,
            ),
            Text(
              "品牌与徽标",
              style: _Style.linkStyle,
            ),
            Text(
              " · ",
              style: _Style.linkStyle,
            ),
            Text(
              "帮助中心",
              style: _Style.linkStyle,
            ),
            Text(
              " · ",
              style: _Style.linkStyle,
            ),
            Text(
              "合作伙伴",
              style: _Style.linkStyle,
            ),
          ],
        ),
        SizedBox.fromSize(
          size: const Size(double.infinity, 48),
        ),
      ],
    );
  }

  Widget getHeaderView(BuildContext context, int index) {
    return Align(
      alignment: Alignment.center,
      child: Container(
          margin: const EdgeInsets.symmetric(vertical: 26, horizontal: 0),
          width: articleListWidth,
          child: AspectRatio(
              aspectRatio: 2.31,
              child: Swiper(
                itemCount: banners.length,
                autoplay: true,
                autoplayDelay: 3000,
                itemBuilder: (BuildContext context, int index) {
                  return Card(
                      clipBehavior: Clip.hardEdge,
                      elevation: 0,
                      shape: const RoundedRectangleBorder(
                          borderRadius:
                              BorderRadius.all(Radius.elliptical(6, 6))),
                      child: Image.network(
                        banners[index]['imageUrl'],
                        fit: BoxFit.cover,
                      ));
                },
              ))),
    );
  }

  Widget getRigthItem(String url) {
    return Container(
      width: infomationListWidth,
      height: infomationListWidth * 0.1786,
      margin: const EdgeInsets.fromLTRB(0, 0, 0, 6),
      clipBehavior: Clip.hardEdge,
      decoration: const BoxDecoration(
          shape: BoxShape.rectangle,
          borderRadius: BorderRadius.all(Radius.elliptical(2, 2))),
      child: Image.network(
        url,
        width: 280,
        height: 50,
        fit: BoxFit.cover,
      ),
    );
  }

  Widget getDownLoadAppView() {
    return Container(
      margin: const EdgeInsets.fromLTRB(0, 6, 0, 0),
      height: infomationListWidth * 0.293,
      decoration: BoxDecoration(
          border: Border.symmetric(
              vertical: BorderSide(color: Colors.grey.shade200, width: 1),
              horizontal: BorderSide(color: Colors.grey.shade200, width: 1)),
          borderRadius: const BorderRadius.all(Radius.elliptical(4, 4))),
      child: Container(
          padding: const EdgeInsets.symmetric(vertical: 0, horizontal: 12),
          child: Row(
            children: [
              Image.network(
                "http://sc.static.xiaotuzhi.top/ali_android.png",
                width: infomationListWidth * 0.214,
                height: infomationListWidth * 0.214,
              ),
              Container(
                padding: const EdgeInsets.fromLTRB(12, 0, 0, 0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    RichText(
                        text: TextSpan(
                            text: "下载简书App",
                            style: TextStyle(
                              fontSize: 14 * middleScale,
                            ),
                            children: [
                          WidgetSpan(
                              child: Icon(
                                Icons.chevron_right,
                                size: 14 * middleScale,
                              ),
                              alignment: PlaceholderAlignment.middle)
                        ])),
                    Text(
                      "随时随地发现和创作内容",
                      style: TextStyle(
                          fontSize: 12 * middleScale, color: Colors.grey),
                    )
                  ],
                ),
              )
            ],
          )),
    );
  }

  Widget getArticleItemView(BuildContext context, int index) {
    dynamic article = articles[index];
    String summary = article["summary"];
    return Container(
        margin: const EdgeInsets.symmetric(vertical: 12, horizontal: 0),
        width: double.infinity,
        child: Flex(
          direction: Axis.horizontal,
          children: [
            Flexible(
                flex: 1,
                fit: FlexFit.tight,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      article["title"],
                      textAlign: TextAlign.start,
                      maxLines: 1,
                      style: const TextStyle(
                          fontSize: 18, fontWeight: FontWeight.bold),
                    ),
                    Container(
                        padding: const EdgeInsets.fromLTRB(0, 12, 12, 12),
                        child: Text(
                          summary.fixAutoLines(),
                          overflow: TextOverflow.ellipsis,
                          textAlign: TextAlign.start,
                          style: const TextStyle(
                              fontSize: 13, color: _Style.textHit),
                          maxLines: article['cover'] != null ? 3 : 2,
                        )),
                    Row(
                      children: [
                        Text(
                          article['author']['nickname'],
                          style: const TextStyle(
                              fontSize: 12, color: _Style.textHit),
                        ),
                        Container(
                            margin: const EdgeInsets.fromLTRB(6, 0, 0, 0),
                            child: RichText(
                                textAlign: TextAlign.center,
                                text: TextSpan(children: [
                                  const WidgetSpan(
                                      alignment: PlaceholderAlignment.middle,
                                      child: Icon(
                                        Icons.comment_rounded,
                                        size: 12,
                                        color: _Style.textHit,
                                      )),
                                  WidgetSpan(
                                      alignment: PlaceholderAlignment.middle,
                                      child: Text(
                                        " ${article['comment']}",
                                        style: const TextStyle(
                                            color: _Style.textHit),
                                      ))
                                ]))),
                        Container(
                          margin: const EdgeInsets.fromLTRB(6, 0, 0, 0),
                          child: RichText(
                              textAlign: TextAlign.center,
                              text: TextSpan(children: [
                                WidgetSpan(
                                    alignment: PlaceholderAlignment.middle,
                                    child: Icon(
                                      Icons.favorite,
                                      size: 12,
                                      color: article['thumbsUp']
                                          ? _Style.thumbsUp
                                          : _Style.textHit,
                                    )),
                                WidgetSpan(
                                    alignment: PlaceholderAlignment.middle,
                                    child: Text(
                                      " ${article['enjoy']}",
                                      style: const TextStyle(
                                          color: _Style.textHit),
                                    ))
                              ])),
                        )
                      ],
                    )
                  ],
                )),
            article['cover'] != null
                ? Card(
                    clipBehavior: Clip.hardEdge,
                    elevation: 0,
                    shape: const RoundedRectangleBorder(
                        side: BorderSide(color: Colors.grey),
                        borderRadius:
                            BorderRadius.all(Radius.elliptical(3, 3))),
                    child: Image.network(
                      article['cover'],
                      width: 150,
                      height: 100,
                      fit: BoxFit.cover,
                    ))
                : const SizedBox.shrink()
          ],
        ));
  }

  Widget getRecomendUserView() {
    return Container(
        margin: const EdgeInsets.fromLTRB(0, 12, 0, 0),
        child: Column(
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                const Text(
                  "推荐作者",
                  style: TextStyle(color: Colors.grey),
                ),
                RichText(
                  text: const TextSpan(children: [
                    WidgetSpan(
                        child: Icon(
                          Icons.loop,
                          color: Colors.grey,
                          size: 16,
                        ),
                        alignment: PlaceholderAlignment.middle),
                    WidgetSpan(
                        child: Text("换一批",
                            style: TextStyle(color: Colors.grey, fontSize: 14)),
                        alignment: PlaceholderAlignment.middle),
                  ]),
                ),
              ],
            ),
            getRecomendUserViewItemView(
                {"userName": "简书钻首席小管家", "wirte": "458.5k", "like": "119.6k"}),
            getRecomendUserViewItemView(
                {"userName": "卢璐说", "wirte": "2184.8k", "like": "34.7k"}),
            getRecomendUserViewItemView(
                {"userName": "王小麦", "wirte": "161.8k", "like": "25.4k"}),
            getRecomendUserViewItemView(
                {"userName": "xiaotuzhi", "wirte": "1.8k", "like": "56"}),
            getRecomendUserViewItemView(
                {"userName": "9527", "wirte": "0.6k", "like": "0.1k"}),
            Container(
              margin: const EdgeInsets.fromLTRB(0, 12, 0, 0),
              height: 34.56,
              alignment: Alignment.center,
              width: double.infinity,
              decoration: const BoxDecoration(
                  //#f7f7f7
                  color: Color(0xfff7f7f7),
                  border: Border.symmetric(
                      vertical: BorderSide(color: Color(0xffdcdcdc), width: 1),
                      horizontal:
                          BorderSide(color: Color(0xffdcdcdc), width: 1)),
                  borderRadius: BorderRadius.all(Radius.elliptical(4, 4))),
              child: RichText(
                  text: const TextSpan(
                      text: "查看全部",
                      style: TextStyle(fontSize: 14, color: Color(0xff787878)),
                      children: [
                    WidgetSpan(
                        child:
                            Icon(Icons.chevron_right, color: Color(0xff787878)),
                        alignment: PlaceholderAlignment.middle)
                  ])),
            )
          ],
        ));
  }

  Widget getRecomendUserViewItemView(dynamic user) {
    return Container(
      height: 67,
      margin: const EdgeInsets.fromLTRB(0, 15, 0, 0),
      child: Stack(
        children: [
          Positioned(
              top: 10,
              left: 10,
              child: Image.asset(
                "assets/images/user_default_icon.png",
                width: 48,
                height: 48,
              )),
          Positioned(
              top: 10,
              left: 70,
              //需要添加right,否则column及其子元素会超出Stack的边界，导致无法换行
              right: 0,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Padding(
                    padding: const EdgeInsets.fromLTRB(0, 0, 60, 0),
                    child: Text(
                      user["userName"].toString().fixAutoLines(),
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                      style: const TextStyle(fontSize: 14),
                    ),
                  ),
                  Padding(
                    padding: const EdgeInsets.fromLTRB(0, 2, 0, 0),
                    child: Text(
                      "写了${user["wirte"]}字 · ${user["like"]}喜欢",
                      style: const TextStyle(color: Colors.grey, fontSize: 11),
                    ),
                  )
                ],
              )),
          Positioned(
              top: 10,
              right: 0,
              child: RichText(
                textAlign: TextAlign.center,
                text: const TextSpan(children: [
                  WidgetSpan(
                      child: Icon(
                        Icons.add,
                        color: Colors.grey,
                        size: 13,
                      ),
                      alignment: PlaceholderAlignment.middle),
                  WidgetSpan(
                      child: Text("关注",
                          style: TextStyle(color: Colors.grey, fontSize: 13)),
                      alignment: PlaceholderAlignment.middle),
                ]),
              ))
        ],
      ),
    );
  }
}

class _Style {
  static const Color textHit = Color(0xff999999);

  static const Color thumbsUp = Color(0xffff0000);

  static const TextStyle linkStyle =
      TextStyle(color: Color(0xff969696), fontSize: 13);

  static double getArticleListWidth(BuildContext context) {
    double width = 625;
    if (MediaQuery.of(context).size.width < (625 + 280 + 24 + 24 * 2 + 100)) {
      width = 485;
    }
    return width;
  }

  static double getMiddleScale(BuildContext context) {
    double scale = 1;
    if (MediaQuery.of(context).size.width < (625 + 280 + 24 + 24 * 2 + 100)) {
      scale = 0.776;
    }
    return scale;
  }

  static double getInfomationListWidth(BuildContext context) {
    double width = 280;
    if (MediaQuery.of(context).size.width < (625 + 280 + 24 + 24 * 2 + 100)) {
      width = 218.75;
    }
    return width;
  }
}
